package com.bilubi.reggie.reggie.common;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
public class CustomDateDeserializer extends JsonDeserializer<Date> {

    private final String dateFormat;

    public CustomDateDeserializer(String dateFormat) {
        this.dateFormat = dateFormat;
    }

    @Override
    public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        String dateStr = p.getText();
        try {
            return new SimpleDateFormat(dateFormat).parse(dateStr);
        } catch (ParseException e) {
            log.info("Failed to parse date:{} with format:{} ", dateStr, dateFormat);
            throw new RuntimeException("Failed to parse date: " + dateStr + " with format: " + dateFormat, e);
        }
    }
}
